package linkList;

import utils.linkListUtil;
import utils.linkListUtil.ListNode;

public class swapPairs {
    //就是迭代，核心就是搞清楚，要修改几条边，那么就要维护几个node变量
    public static ListNode swapPairs(ListNode head) {
        if (head==null||head.next==null) {
            return head;
        }

        ListNode curr=head,next=head.next,pre=null,rt=next;
        while (curr!=null&&next!=null) {
            // 1 2 3 4 5 6
            // 要修改三个指针，pre curr next
            curr.next=next.next;
            next.next=curr;
            if (pre!=null) {
                pre.next=next;
            }
            if (curr.next==null) {
                break;
            }
            // 迭代
            pre=curr;
            curr=curr.next;
            next=curr.next;
        }
        return rt;

    }
    public static void main(String[] args) {
        int[] l1 = new int[] { 1, 2,3,4,5,6 };
        ListNode list1 = linkListUtil.createLinkedList(l1);
        ListNode mergeTwoLists = swapPairs(list1);
        while (mergeTwoLists != null) {
            System.out.println(mergeTwoLists.val);
            mergeTwoLists = mergeTwoLists.next;
        }
    }
}
